<script setup lang="ts">
import { getConsultOrderPayUrl } from '@/services/consult'
import { showLoadingToast, showToast } from 'vant'
import { ref } from 'vue'

const { orderId, payCallback } = defineProps<{
  show: boolean // 外部控制抽屉显示和隐藏
  onClose?: () => void // 关闭抽屉要处理的业务(由父组件处理)
  actualPayment: number // 实付金额
  orderId: string // 订单id
  payCallback: string // 支付成功回跳地址
}>()

defineEmits<{
  (e: 'update:show', val: boolean): void
}>()

// 支付方式: 0 微信支付  1 支付宝支付
const paymentMethod = ref<0 | 1>()

// 6. 跳转支付
const pay = async () => {
  // 6.1 判断是否选择支付方式
  if (!paymentMethod.value) return showToast('请选择支付方式')
  showLoadingToast('跳转支付')
  // 6.2 调用获取跳转地址的接口
  const res = await getConsultOrderPayUrl({
    paymentMethod: paymentMethod.value,
    orderId: orderId,
    // 'http://127.0.0.1:5173/room'
    payCallback: import.meta.env.VITE_APP_CALLBACK + payCallback
  })
  // 6.3 跳转
  window.location.href = res.data.payUrl
}
</script>

<template>
  <!-- 支付抽屉 -->
  <van-action-sheet
    :show="show"
    @update:show="$emit('update:show', $event)"
    title="选择支付方式"
    :close-on-popstate="false"
    :closeable="false"
    :before-close="onClose"
  >
    <div class="pay-type">
      <p class="amount">¥{{ actualPayment.toFixed(2) }}</p>
      <van-cell-group>
        <van-cell title="微信支付" @click="paymentMethod = 0">
          <template #icon>
            <cp-icon name="consult-wechat"></cp-icon>
          </template>
          <template #extra>
            <van-checkbox :checked="paymentMethod === 0"></van-checkbox>
          </template>
        </van-cell>
        <van-cell title="支付宝支付" @click="paymentMethod = 1">
          <template #icon>
            <cp-icon name="consult-alipay"></cp-icon>
          </template>
          <template #extra>
            <van-checkbox :checked="paymentMethod === 1"></van-checkbox>
          </template>
        </van-cell>
        <div class="btn">
          <van-button type="primary" block round @click="pay"
            >立即支付</van-button
          >
        </div>
      </van-cell-group>
    </div>
  </van-action-sheet>
</template>

<style lang="scss" scoped>
.pay-type {
  .amount {
    padding: 20px;
    text-align: center;
    font-size: 16px;
    font-weight: bold;
  }
  .btn {
    padding: 15px;
  }
  .van-cell {
    align-items: center;
    .cp-icon {
      margin-right: 10px;
      font-size: 18px;
    }
    .van-checkbox :deep(.van-checkbox__icon) {
      font-size: 16px;
    }
  }
}
</style>
